package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.EmpEarlyWarnResultMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预警结果Service业务层处理
 *
 * @author zsl
 * @date 2024-04-15
 */
@Service
@Slf4j
public class EmpEarlyWarnResultServiceImpl extends ServiceImpl<EmpEarlyWarnResultMapper, EmpEarlyWarnResult> implements IEmpEarlyWarnResultService {
    @Autowired
    private IEmpNormCollectService iEmpNormCollectService;
    @Autowired
    private IEmpModelSchemeService iEmpModelSchemeService;
    @Autowired
    private IEmpNormSystemService iEmpNormSystemService;
    @Autowired
    private IEmpAreaService iEmpAreaService;

    /**
     * 查询预警结果
     *
     * @param id 预警结果主键
     * @return 预警结果
     */
    @Override
    public EmpEarlyWarnResult selectEmpEarlyWarnResultById(Long id) {
        return this.baseMapper.selectEmpEarlyWarnResultById(id);
    }

    /**
     * 查询预警结果列表
     *
     * @param empEarlyWarnResult 预警结果
     * @return 预警结果
     */
    @Override
    public List<EmpEarlyWarnResult> selectEmpEarlyWarnResultList(EmpEarlyWarnResult empEarlyWarnResult) {
        List<EmpEarlyWarnResult> list = this.baseMapper.selectEmpEarlyWarnResultList(empEarlyWarnResult);

        list.forEach(item -> {
            //查询采集和区域
            if (ObjectUtils.isNotEmpty(item.getCollectId())) {
                EmpNormCollect collect = iEmpNormCollectService.selectEmpNormCollectById(item.getCollectId());
                if (ObjectUtils.isNotEmpty(collect)) {
                    EmpNormSystem empNormSystem = iEmpNormSystemService.selectEmpNormSystemById(collect.getSystemId());
                    if (ObjectUtils.isNotEmpty(empNormSystem)) {
                        collect.setEmpNormSystem(empNormSystem);
                    }
                    EmpArea empArea = iEmpAreaService.selectEmpAreaById(collect.getAreaId());
                    if (ObjectUtils.isNotEmpty(empArea)) {
                        collect.setEmpArea(empArea);
                    }
                    item.setNormCollect(collect);
                }
            }
            //查询方案
            if (ObjectUtils.isNotEmpty(item.getSchemeId())) {
                EmpModelScheme empModelScheme = iEmpModelSchemeService.selectEmpModelSchemeById(item.getSchemeId());
                if (ObjectUtils.isNotEmpty(empModelScheme)) {
                    item.setEmpModelScheme(empModelScheme);
                }
            }
        });

        return list;
    }

    /**
     * 新增预警结果
     *
     * @param empEarlyWarnResult 预警结果
     * @return 结果
     */
    @Override
    public int insertEmpEarlyWarnResult(EmpEarlyWarnResult empEarlyWarnResult) {
        empEarlyWarnResult.setCreateTime(DateUtils.getNowDate());
        log.info("新增预警结果:{}", JSON.toJSONString(empEarlyWarnResult));
        return this.baseMapper.insertEmpEarlyWarnResult(empEarlyWarnResult);
    }

    /**
     * 修改预警结果
     *
     * @param empEarlyWarnResult 预警结果
     * @return 结果
     */
    @Override
    public int updateEmpEarlyWarnResult(EmpEarlyWarnResult empEarlyWarnResult) {
        empEarlyWarnResult.setUpdateTime(DateUtils.getNowDate());
        return this.baseMapper.updateEmpEarlyWarnResult(empEarlyWarnResult);
    }

    /**
     * 批量删除预警结果
     *
     * @param ids 需要删除的预警结果主键
     * @return 结果
     */
    @Override
    public int deleteEmpEarlyWarnResultByIds(Long[] ids) {
        return this.baseMapper.deleteEmpEarlyWarnResultByIds(ids);
    }

    /**
     * 删除预警结果信息
     *
     * @param id 预警结果主键
     * @return 结果
     */
    @Override
    public int deleteEmpEarlyWarnResultById(Long id) {
        return this.baseMapper.deleteEmpEarlyWarnResultById(id);
    }

    @Override
    public String importEmpEarlyWarnResult(List<EmpEarlyWarnResult> empEarlyWarnResults, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(empEarlyWarnResults) || empEarlyWarnResults.isEmpty()) {
            return "导入预警结果数据不能为空";
        }
        int successNum = 0;
        int failureNum = 0;
        int count = 0;
        Date nowDate = DateUtils.getNowDate();
        StringBuilder failureMsg = new StringBuilder();
        try {
            for (EmpEarlyWarnResult result : empEarlyWarnResults) {
                count++;
                if (StringUtils.isAnyBlank(result.getYear(), result.getAttributeName(), result.getAreaName())) {
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 行数据，").append("时间、属性名称、区域名称不能为空，请检查后重新导入");
                    failureNum++;
                    continue;
                }
                //根据时间、属性名称、区域名称查找采集表的一条数据
                EmpNormSystem empNormSystem = iEmpNormSystemService.selectEmpNormSystemByName(result.getAttributeName());
                if (ObjectUtils.isEmpty(empNormSystem)) {
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 行数据，").append("属性名称不存在，请检查后重新导入");
                    failureNum++;
                    continue;
                }
                EmpArea empArea = iEmpAreaService.selectEmpAreaByName(result.getAreaName());
                if (ObjectUtils.isEmpty(empArea)) {
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 行数据，").append("区域名称不存在，请检查后重新导入");
                    failureNum++;
                    continue;
                }
                LambdaQueryWrapper<EmpNormCollect> wrapper = Wrappers.lambdaQuery(EmpNormCollect.class)
                        .eq(EmpNormCollect::getYear, result.getYear())
                        .eq(EmpNormCollect::getSystemId, empNormSystem.getId())
                        .eq(EmpNormCollect::getAreaId, empArea.getId());
                List<EmpNormCollect> collectList = iEmpNormCollectService.list(wrapper);
                if (ObjectUtils.isEmpty(collectList)) {
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 行数据，").append("指标采集数据不存在，请检查后重新导入");
                    failureNum++;
                    continue;
                }
                result.setCollectId(collectList.get(0).getId());
                //根据方案名称查找方案表的一条数据
                if (StringUtils.isNotBlank(result.getModelSchemeName())) {
                    EmpModelScheme empModelScheme = iEmpModelSchemeService.selectEmpModelSchemeByName(result.getModelSchemeName());
                    if (ObjectUtils.isEmpty(empModelScheme)) {
                        failureMsg.append("<br/>").append("第 ").append(count).append(" 行数据，").append("方案名称不存在，请检查后重新导入");
                        failureNum++;
                        continue;
                    }
                    result.setSchemeId(empModelScheme.getId());
                }

                if (ObjectUtils.isEmpty(result.getId())) {
                    //新增
                    result.setCreateBy(operName);
                    result.setCreateTime(nowDate);
                } else {
                    EmpEarlyWarnResult byId = this.getById(result.getId());
                    if (ObjectUtils.isNotEmpty(byId)) {
                        //更新
                        result.setUpdateBy(operName);
                        result.setUpdateTime(nowDate);
                    } else {
                        //新增
                        result.setCreateBy(operName);
                        result.setCreateTime(nowDate);
                    }
                }
                successNum++;
            }

            //数据校验
            List<EmpEarlyWarnResult> resultList = empEarlyWarnResults.stream().filter(res -> ObjectUtils.allNotNull(res.getCollectId()) && StringUtils.isNotEmpty(res.getYear())).collect(Collectors.toList());

            if (isUpdateSupport) {
                this.saveOrUpdateBatch(resultList);
            } else {
                //批量新增
                resultList = resultList.stream().filter(col -> ObjectUtils.isNotEmpty(col.getCreateTime())).collect(Collectors.toList());
                this.saveBatch(resultList);
            }
        } catch (Exception e) {
            log.error("批量导入预警结果数据异常：", e);
        }

        String resultMsg = "导入完成，总数量：" + empEarlyWarnResults.size() + "，成功数量：" + successNum + "，失败数量：" + failureNum;
        if (StringUtils.isNotEmpty(failureMsg.toString())) {
            resultMsg = resultMsg + "<br/>错误原因如下：<br/>" + failureMsg;
        }
        return resultMsg;
    }
}
